package cn.moukou.sbzz.service;

import cn.moukou.sbzz.mapper.BankMapper;
import cn.moukou.sbzz.pojo.Bank;
import cn.moukou.sbzz.util.JwtUtil;
import cn.moukou.sbzz.util.Md5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.file.Watchable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BankService {

    @Autowired
    BankMapper bankMapper;

    public Bank bankLogin(String uid, String pwd) throws Exception {
        Bank bank = bankMapper.selectById(uid);
        if(bank == null) {
            return null;
        }

        if (Md5Util.getMD5String(pwd).equals(bank.getPwd())) {
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("uid", uid);
            tokenMap.put("role", "bank");
            String token = JwtUtil.generateToken(tokenMap, 6000);
            bank.setPwd(token);
            return bank;
        } else {
            return null;
        }
    }

    public List<Bank> getBankList() {
        return bankMapper.selectList(null);
    }

    public List<Bank> getBankToAuth() {
        QueryWrapper<Bank> wrapper = new QueryWrapper<>();
        wrapper.eq("auth", 1);
        return bankMapper.selectList(wrapper);
    }

    public int authBank(String id) {
        Bank bank = bankMapper.selectById(id);
        if(bank == null) {
            return 0;
        }
        bank.setAuth(2);
        return bankMapper.updateById(bank);
    }

    public int submitBank(String id, String name, String detail, String link) {
        Bank bank = bankMapper.selectById(id);
        bank.setName(name);
        bank.setDetail(detail);
        bank.setLink(link);
        bank.setAuth(1);
        return bankMapper.updateById(bank);
    }

    public int accessBank(String id, String form, String business, String pool) {
        Bank bank = bankMapper.selectById(id);
        if(bank == null) {
            return 0;
        }
        bank.setFormAccess(form);
        bank.setBusinessAccess(business);
        bank.setPoolAccess(pool);
        return bankMapper.updateById(bank);
    }

    public Bank getOneBank(String id) {
        return bankMapper.selectById(id);
    }

}
